﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.NEWPhotoRindGrid.IView;
using System.Windows.Forms;
using MINERP.BLL.NewPhotoRindGrid;
using MINERP.MODEL.NewPhotoRindGrid;
using System.Drawing;
using MINERP.COM;
using System.Diagnostics;
using System.Text.RegularExpressions;
using MINERP.MODEL.FoundationModel;
using System.Data;
using FastReport;
using DonnetSpeech;
using System.Runtime.InteropServices;
using Leadtools.WinForms;
using Leadtools;
using Leadtools.Codecs;
using System.Threading;
using MINERP.NEWPhotoRindGrid.Forms;
using MINERP.PhotoRindGrid.Forms;
using System.IO;

namespace MINERP.NEWPhotoRindGrid.Presenter
{

    /// <summary>
    /// 界面上格子的状态
    /// </summary>
    public enum UCGridStatus
    {
        TimeOut,//超时
        Priority,//加急，可以再细分
        OutOver,//此单的所有片都已出完但还未全进格子
        Selected,//被选中,级别最高
        Normal//一般状态
    }

    public class MyDefineGrid
    {
        public UCGrid UCg { get; set; }
        public GridInfo_Grid gridInfo { get; set; }
    }

    public class MainPresenter
    {
        private const int WarnPriority = 6;//需要在打印时报警的最低加急级别
        private const String FACOTRYNAME = "冲印车间";//在分片小票上显示车间的名称

        SpeekMsgDelegate dlSpeak;//发音
        PrintGridDeleGate dlPrint; //打印

        Report fasrReport = new Report();



        private IMainView _view;
        private MainBLL _mainBLL;

        int UGridWidth;
        int UGridHeigth;

        private List<MyDefineGrid> _curSelectedGridList = new List<MyDefineGrid>();//当前选中的格子集

        private Dictionary<int, MyDefineGrid> GirdControls;//存放所有格子信息
        GridInfo_Grid gridViewInfo;

        public MainPresenter(IMainView view)
        {
            _view = view;
            _mainBLL = new MainBLL();

            SelectSubArea();
            //加载报表
            fasrReport.Load(Application.StartupPath + "\\Report\\分片小票.frx");

            dlSpeak = SpeekMsg;//发音
            dlPrint = PintGrid; //打印
        }

        [DllImport("USER32.dll")]
        static extern short GetKeyState(int nVirtKey);
        const int VK_CONTROL = 0x11;

        /// <summary>
        /// 设置当前选中的格子,
        /// </summary>
        /// <param name="myGrid"></param>

        private void SetGridSelected(MyDefineGrid myGrid)
        {
            if (myGrid == null)
            {
                return;
            }
            int type = 1; //new
            if (_curSelectedGridList != null && _curSelectedGridList.Count > 0)
            {
                if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下CTRL键
                {
                    type = 1;
                    if (_curSelectedGridList.Count == 1 && _curSelectedGridList.Contains(myGrid))
                    {
                        return;
                    }
                    ReSetGridStatusAndCurCount(_curSelectedGridList);//还原上一些格子本来的状态
                }
                else//添加
                {
                    type = 0;
                }
            }

            if (myGrid.UCg.GridStatus == UCGridStatus.Selected)
            {
                if (type == 0)//按下CTRL
                {
                    if (_curSelectedGridList.Count > 1)
                    {
                        //从选择列表中删除此格子
                        SetSelectGridList(myGrid, 3);
                        //再还原其原来的状态
                        ReSetGridStatusAndCurCount(new List<MyDefineGrid>() { myGrid });//还原上一些格子本来的状态
                    }
                }
                else//没有按下CTRL
                {
                    SetSelectGridList(myGrid, type);
                    myGrid.UCg.GridStatus = UCGridStatus.Selected;
                }
            }
            else
            {
                SetSelectGridList(myGrid, type);
                myGrid.UCg.GridStatus = UCGridStatus.Selected;
            }

        }

        /// <summary>
        /// 根据点击选中时的操作怎样向选中_curSelectedGridList添加数据
        /// </summary>
        /// <param name="selectedGrids"></param>
        /// <param name="type">0:add,1:new,2:删除</param>
        private void SetSelectGridList(MyDefineGrid selectedGrid, int type)
        {
            if (type == 0)
            {
                if (!_curSelectedGridList.Contains(selectedGrid))
                {
                    _curSelectedGridList.Add(selectedGrid);
                }

            }
            else if (type == 1)
            {
                _curSelectedGridList.Clear();
                if (selectedGrid != null)
                {
                    _curSelectedGridList.Add(selectedGrid);

                }
            }
            else if (type == 3)//从列表中删除
            {
                _curSelectedGridList.Remove(selectedGrid);
            }
            SetFrmBtnEnable();
        }

        private void SetFrmBtnEnable()
        {
            _view.setClearBtnEnable = true;
            _view.setSelectedClearBoxEnable = true;
            if (_curSelectedGridList.Count > 1)
            {
                _view.setPrintBtnEnable = false;//将打印按钮变得不可用
            }
            else if (_curSelectedGridList.Count == 1)
            {
                _view.setPrintBtnEnable = true;
            }
            else//==0
            {
                _view.setClearBtnEnable = false;
                _view.setSelectedClearBoxEnable = false;
                _view.setPrintBtnEnable = false;//将打印按钮变得不可用
            }
        }


        //选择分区信息
        private void SelectSubArea()
        {
            FrmSelectSubarea frm = new FrmSelectSubarea();
            if (DialogResult.OK == frm.ShowDialog()) { IniFrm(); }
        }

        //初始化界面信息
        private void IniFrm()
        {

            #region test
            //string strTest = "A1" + "测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江测试淋江";
            //SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            //SpVoice Voice = new SpVoice();
            //Voice.WaitUntilDone(-1);
            //Voice.Speak(strTest, SpFlags);



            #endregion

            Size screenSize = _view.GetDisplaySize;//获取屏的工作区域
            //UGridWidth = screenSize.Width / DataTransfer.CurSubArea.WidthNum - 7;
            //UGridHeigth = (screenSize.Height - 60) / DataTransfer.CurSubArea.HeightNum - 7;
            UGridWidth = screenSize.Width / DataTransfer.CurSubArea.HeightNum - 7;
            UGridHeigth = (screenSize.Height - 60) / DataTransfer.CurSubArea.WidthNum - 7;

            int result = 0;
            List<GridInfo_Grid> listGrid = null;
            result = _mainBLL.GetGridInfoBySubAreaId(DataTransfer.CurSubArea.SubAreaID, out listGrid);
            if (result == 0)//成功
            {
                //将GridInfo_Grid转化为UCGrid控件
                IntiUCGrid(listGrid);
                SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一个为选中状态
                DisPlayGrid();
            }
            else if (result == 2)//没有找到格子信息
            {

            }
            else if (result == 1)//输入的参数不对
            {

            }
            else if (result == 3)//从数据库取数据时出错
            {

            }
        }

        public void DisPlayGrid()
        {
            _view.DisPlayGrid(GirdControls.Values.Select(g => g.UCg).ToList());
        }

        /// <summary>
        /// 将条码转换为ID
        /// </summary>
        /// <param name="strBarCode"></param>
        /// <returns></returns>
        private int ConvertBarCodeToId(string strBarCode)
        {
            if (strBarCode.Length == 10)
            {
                try
                {
                    return Convert.ToInt32(strBarCode.Substring(1));
                }
                catch (Exception)
                {
                    return 0;
                }

            }
            return 0;
        }

        public void AssignGrid()//分配格子
        {
            int result = 1;

            string photoBarCode = string.Empty;
            string strNextTechName = string.Empty;
            string strPeak = string.Empty;//发音需要说的话
            string shopGridName = string.Empty;//商户分堆的格子号
            string outProductOrderInBag=string.Empty;//产品在订单中的序号
            string outShopName = string.Empty;
            int IsPrint;
            int gridId;
            int curSubAreadId = DataTransfer.CurSubArea.SubAreaID;
            int opUid = DataTransfer.OpUid;
            int curTechId = DataTransfer.curTechId;
            int curOrderProductId;
            bool isInGird = false;
            bool isNewGrid = false;



            MyDefineGrid curGrid;
            PhotoInfo_Info temPi = null;
            MainBLL _mainBLL;
            GridBLL_Grid _gridBll = new GridBLL_Grid();

            photoBarCode = ConvertToPhotoBarCode(_view.InpuPhotoCode);
            if (photoBarCode == null)
            {
                MessageBox.Show("输入的字符不合法，请重新输入！");
                return;
            }

            curGrid = default(MyDefineGrid);

            #region 先自已在格子中找一次，如果没有找到再从数据库中找
            foreach (var mg in GirdControls.Values)
            {
                if (mg.gridInfo.OrderInfo != null)
                {
                    temPi = mg.gridInfo.OrderInfo.PhotoS.Find(p => p.PhotoBarCode == photoBarCode);
                    if (temPi != null)
                    {
                        if (temPi.Status == (int)PhotoStatus.FenPian)
                        {
                            strPeak = mg.gridInfo.GridBaseInfo.GridName+"重复";
                        }
                        curGrid = mg;
                        isInGird = true;
                        break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(strPeak))
            {
                dlSpeak.BeginInvoke(strPeak, false, null, null);
                SetGridSelected(curGrid);//设置选中的格子
                return;
            }
            #endregion

            _mainBLL = new MainBLL();
            result = _mainBLL.AssignGridByPhotoCode(photoBarCode, out IsPrint, out gridId, curSubAreadId, opUid, out gridViewInfo, out strNextTechName, curTechId, out isNewGrid, out curOrderProductId, out shopGridName, _view.IsAutoAssign,out  outProductOrderInBag,out outShopName);
            if (result == 1)//成功
            {
                if (gridId != 0)
                {
                    GirdControls.TryGetValue(gridId, out curGrid);
                }
                if (curGrid == null && IsPrint != 2)
                {
                    bool isComplete = false;
                    string OGridName = "";
                    string SubAreaName = _mainBLL.GetGridSubAreasNameBYGridID(gridId, Convert.ToInt32(photoBarCode.Substring(1)), out  isComplete, out  OGridName);
                    if (isComplete)
                    {
                        MessageBox.Show("请再扫一次，打印出小片，并取出" + SubAreaName + "中的" + OGridName + "格子中的照片，送到" + strNextTechName);
                    }
                    else
                    {
                        //MessageBox.Show("此照片在" + SubAreaName);
                        dlSpeak.BeginInvoke("此照片在" + SubAreaName + "的" + OGridName + "格子中", false, null, null);
                    }
                    return;
                }

                if (IsPrint == 0)
                {
                    if (isNewGrid)
                    {
                        //更新显示
                        curGrid.gridInfo = gridViewInfo;
                        //curGrid.UCg = CreateUcgGrid(gridViewInfo);
                        ReSetUCGrid(curGrid.UCg, gridViewInfo);

                    }
                    else
                    {
                        if (isInGird)
                        {
                            //更新显示
                            temPi.Status = (int)PhotoStatus.FenPian;
                            curGrid.UCg.CurPicCount += 1;
                            //ReSetGridStatus(curGrid);
                        }
                        else
                        {
                            //更新显示
                            GridBLL_Grid _bllGrid = new GridBLL_Grid();
                            curGrid.gridInfo = _bllGrid.GetGridViewInfoByGridId(gridId, curOrderProductId);
                            //curGrid.UCg = CreateUcgGrid(curGrid.gridInfo);
                            ReSetUCGrid(curGrid.UCg, curGrid.gridInfo);
                        }
                    }

                    //语单提示
                    strPeak = curGrid.UCg.GridName;
                    dlSpeak.BeginInvoke(strPeak, false, null, null);
                    //设置选中的格子
                    SetGridSelected(curGrid);
                }
                else if (IsPrint == 1)//完成
                {

                    //语音提示
                    strPeak = curGrid.UCg.GridName;
                    GridInfo_Grid printGridInfo = curGrid.gridInfo;

                    int photoId = ConvertBarCodeToId(photoBarCode);

                    if (isInGird)
                    {
                        //if (curGrid.gridInfo.OrderInfo.Remark.Contains("淋膜") || curGrid.gridInfo.OrderInfo.OrderProductName.Contains("淋膜"))
                        //{
                        //    strPeak += "淋膜";
                        //}
                        //else if (curGrid.gridInfo.OrderInfo.Remark.Contains("冷裱") || curGrid.gridInfo.OrderInfo.OrderProductName.Contains("冷裱"))
                        //{
                        //    strPeak += "冷裱";
                        //}

                        //if (curGrid.gridInfo.OrderInfo.Remark.Contains("转") || curGrid.gridInfo.OrderInfo.OrderProductName.Contains("转"))
                        //{
                        //    strPeak += curGrid.gridInfo.OrderInfo.Remark.Substring(curGrid.gridInfo.OrderInfo.Remark.IndexOf("转"), 2);
                        //}

                        //strPeak += ",完成" + strNextTechName;
                        //strPeak += ",完成";
                        //dlSpeak.BeginInvoke(strPeak, true, null, null);
                        ////SpeekMsg(strPeak, true);

                        ////从内存中组织打印数据
                        //PintGrid(curGrid.gridInfo, strNextTechName, shopGridName);
                        //清空格子
                        //curGrid.gridInfo.OrderInfo = null;
                        //ReSetUCGrid(curGrid.UCg, null);
                        //SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下

                        PhotoInfo_Info pi = curGrid.gridInfo.OrderInfo.PhotoS.FirstOrDefault(p => p.PhotoId == photoId);
                        if (pi.IsRebackPhoto)
                        {
                            strPeak += "，返单完成";
                        }
                        else
                        {
                            strPeak += ",完成";
                        }

                    }
                    else//只有一张片
                    {
                        if (gridViewInfo.OrderInfo == null)
                        {
                            OrderInfoBLL_Grid _orderBLL = new OrderInfoBLL_Grid();
                            OrderInfo_Grid oi;
                            _orderBLL.GetOrderInfo_Grid(curOrderProductId, out oi);
                            gridViewInfo.OrderInfo = oi;
                        }


                        //if (gridViewInfo.OrderInfo.Remark.Contains("淋膜") || gridViewInfo.OrderInfo.OrderProductName.Contains("淋膜"))
                        //{
                        //    strPeak += "淋膜";
                        //}
                        //else if (gridViewInfo.OrderInfo.Remark.Contains("冷裱") || gridViewInfo.OrderInfo.OrderProductName.Contains("冷裱"))
                        //{
                        //    strPeak += "冷裱";
                        //}

                        //if (gridViewInfo.OrderInfo.Remark.Contains("转") || gridViewInfo.OrderInfo.OrderProductName.Contains("转"))
                        //{
                        //    strPeak += gridViewInfo.OrderInfo.Remark.Substring(curGrid.gridInfo.OrderInfo.Remark.IndexOf("转"), 2);
                        //}

                        ////strPeak += ",完成" + strNextTechName;
                        //strPeak += ",完成";
                        //dlSpeak.BeginInvoke(strPeak, true, null, null);
                        //SpeekMsg(strPeak, true);
                        //1.从数据库中组织打印信息
                        //dlPrint.BeginInvoke(gridViewInfo, strNextTechName, shopGridName, null, null);
                        //PintGrid(gridViewInfo, strNextTechName, shopGridName);

                        printGridInfo = gridViewInfo;
                        PhotoInfo_Info pi = gridViewInfo.OrderInfo.PhotoS.FirstOrDefault(p => p.PhotoId == photoId);
                        if (pi.IsRebackPhoto)
                        {
                            strPeak += "，返单完成";
                        }
                        else
                        {
                            strPeak += ",完成";
                        }
                    }


                    strPeak += strNextTechName;


                    dlSpeak.BeginInvoke(strPeak, true, null, null);
                    //SpeekMsg(strPeak, true);

                    //从内存中组织打印数据
                    PintGrid(printGridInfo, strNextTechName, shopGridName, outProductOrderInBag,outShopName);

                    //打印数据
                    if (isInGird)
                    {
                        //清空格子
                        curGrid.gridInfo.OrderInfo = null;
                        ReSetUCGrid(curGrid.UCg, null);
                        SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下
                    }

                }
                else if (IsPrint == 2)
                {
                    //询问是否需要重新打印
                    if (DialogResult.Yes == MessageBox.Show("此单已完成，是否需要重新打印?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        if (isInGird)
                        {
                            //从内存中组织打印数据 
                            PintGrid(curGrid.gridInfo, strNextTechName, shopGridName, outProductOrderInBag,outShopName);
                            //清空格子
                            curGrid.gridInfo.OrderInfo = null;
                            ReSetUCGrid(curGrid.UCg, null);
                            SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下
                        }
                        else
                        {
                            //从数据库中组织打印数据
                            OrderInfoBLL_Grid _orderBLL = new OrderInfoBLL_Grid();
                            OrderInfo_Grid oi;
                            _orderBLL.GetOrderInfo_Grid(curOrderProductId, out oi);
                            PintGrid(new GridInfo_Grid() { OrderInfo = oi, GridBaseInfo = new Grid_Info() { GridName = " " } }, "重复打印", shopGridName, outProductOrderInBag,"");
                        }
                    }


                    if (isInGird)
                    {
                        //从内存中清除数据
                        curGrid.gridInfo.OrderInfo = null;
                        ReSetUCGrid(curGrid.UCg, null);
                        SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下
                    }
                }
            }
            else if (result == -1)
            {
                MessageBox.Show("没有找到此照片的信息，请确认输入是否正确？");
            }
            else if (result == -5)
            {
                MessageBox.Show("没有可用的格子！");
            }
        }

        
        private byte [] MakeThumbnail(GridInfo_Grid gridInfo)
        {
            byte [] img=new byte[10];
            if (gridInfo.OrderInfo.IsPrintThumbnail)
            {
                PhotoInfo_Info pi= gridInfo.OrderInfo.PhotoS.OrderBy(p => p.PhotoName).First();
                img = GetPicBytes(pi.PicPath);
            }
            return img;
 
        }

        private byte[] GetPicBytes(string picPath)
        {
            byte[] img;
            using (Image IM = Image.FromFile(picPath))
            {

                using (Image pThumbnail = IM.GetThumbnailImage(200, 200, null, IntPtr.Zero))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        pThumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        img = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(img, 0, Convert.ToInt32(ms.Length));
                        ms.Close();
                        ms.Dispose();
                    }
                    pThumbnail.Dispose();
                }

                IM.Dispose();
            }
            return img;

        }

        #region 发音与打印
        private delegate void SpeekMsgDelegate(string strMsg, bool isNeedReadCompleted);

        SpVoice Voice = new SpVoice();
        SpeechVoiceSpeakFlags SpFlags;
        /// <summary>
        /// 发音
        /// </summary>
        /// <param name="strMsg"></param>
        public void SpeekMsg(string strMsg, bool isNeedReadCompleted)
        {
            //更新界面的显示,"A1,此单已完成"
            string gridName = strMsg.Split(new char[] { ',' })[0];
            _view.ShowGridName(gridName);
            //Application.DoEvents();            




            if (isNeedReadCompleted)
            {
                Voice.Priority = SpeechVoicePriority.SVPAlert;
                SpFlags = SpeechVoiceSpeakFlags.SVSFDefault;
                //_view.setClearBtnEnable = false;
                //Voice.WaitUntilDone(-1);
            }
            else
            {
                SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            }
            //SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            //Voice.GetVoices(string.Empty, string.Empty).Item(3);//0:男生，3女生
            Voice.Speak(strMsg.Substring(1), SpFlags);//将A去掉直接读格子号

            //if (isNeedReadCompleted)
            //{
            //    _view.setClearBtnEnable = true;
            //}

        }


        //用于异步调用打印的委托
        private delegate void PrintGridDeleGate(GridInfo_Grid gInfo, string nextTechName, string shopGridName, string outProductOrderInBag,string outShopName);
        /// <summary>
        /// 打印格子里的内容
        /// </summary>
        /// <param name="gInfo"></param>
        public void PintGrid(GridInfo_Grid gInfo, string nextTechName, string shopGridName, string outProductOrderInBag,string outShopName)
        {

            if (!Properties.Settings.Default.IsPrintTicket)
            {
                return;
            }
            //分为二部分：1、照片尺寸归类信息，用TABLE格式
            DataTable dt = new DataTable("PhotoSize");
            dt.Columns.Add("Size", typeof(string));
            dt.Columns.Add("Num", typeof(int));

            DataTable DtInfo = new DataTable("DtInfo");
            DtInfo.Columns.Add("CtmName", typeof(string));
            DtInfo.Columns.Add("OrderProductName", typeof(string));
            DtInfo.Columns.Add("OrderRemark", typeof(string));
            DtInfo.Columns.Add("ShopName", typeof(string));
            DtInfo.Columns.Add("OrderBarCode", typeof(string));
            DtInfo.Columns.Add("NextTechName", typeof(string)); 
            DtInfo.Columns.Add("GridName", typeof(string));
            DtInfo.Columns.Add("PriorityRemark", typeof(string));
            DtInfo.Columns.Add("FactoryName", typeof(string));
            DtInfo.Columns.Add("ShopGridName", typeof(string));
            DtInfo.Columns.Add("FetchTime", typeof(string));
            DtInfo.Columns.Add("PhotosCount", typeof(int));
            DtInfo.Columns.Add("outProductOrderInBag", typeof(string));
            DtInfo.Columns.Add("IsPrintThumbnail", typeof(bool));
            
            int photosCount = 0;
            decimal photosAreas = 0;
            foreach (var item in gInfo.OrderInfo.PhotoS.GroupBy(p => p.PhtotoSizeInch + "(in) (" + p.PhotoSizeCm + ")cm").ToList())
            {
                dt.Rows.Add(new object[] { item.Key, item.Count() });
                //photosCount += item.Count();
            }
            //DtInfo.Rows.Add(new object[] { gInfo.OrderInfo.CtmName.Replace('[', '(').Replace(']', ')') });
            //DtInfo.Rows.Add(new object[] { "OrderProductName", gInfo.OrderInfo.OrderProductName.Replace('[', '(').Replace(']', ')') });
            //DtInfo.Rows.Add(new object[] { "OrderRemark", gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')') });
            //DtInfo.Rows.Add(new object[] { "ShopName", gInfo.OrderInfo.ShopName });
            //DtInfo.Rows.Add(new object[] { "OrderBarCode", gInfo.OrderInfo.OrderProductId.ToString() });
            //DtInfo.Rows.Add(new object[] { "NextTechName", nextTechName });
            //DtInfo.Rows.Add(new object[] { "PriorityRemark", gInfo.OrderInfo.OrderPriority >= WarnPriority ? "急件" + gInfo.OrderInfo.OrderPriority.ToString() : "" });
            //DtInfo.Rows.Add(new object[] { "FactoryName", FACOTRYNAME });
            //DtInfo.Rows.Add(new object[] { "ShopGridName", shopGridName });
            //DtInfo.Rows.Add(new object[] { "FetchTime", gInfo.OrderInfo.FetchTime });
            //DtInfo.Rows.Add(new object[] { "PhotosCount", photosCount });
            DataRow titleRow = DtInfo.NewRow();
            titleRow["CtmName"] = gInfo.OrderInfo.CtmName.Replace('[', '(').Replace(']', ')');
            titleRow["OrderProductName"] = gInfo.OrderInfo.OrderProductName.Replace('[', '(').Replace(']', ')');
            titleRow["OrderRemark"] = gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')');
            titleRow["ShopName"] = gInfo.OrderInfo.ShopName;
            titleRow["OrderBarCode"] = "*"+gInfo.OrderInfo.OrderProductId.ToString()+"*";
            titleRow["NextTechName"] = nextTechName;
            titleRow["PriorityRemark"] = gInfo.OrderInfo.OrderPriority >= WarnPriority ? "急件" + gInfo.OrderInfo.OrderPriority.ToString() : "" ;
            titleRow["FactoryName"] =FACOTRYNAME;
            titleRow["ShopGridName"] = shopGridName;
            titleRow["FetchTime"] = gInfo.OrderInfo.FetchTime;
            titleRow["GridName"] = string.IsNullOrEmpty(gInfo.GridBaseInfo.GridName) ? "重复打印" : gInfo.GridBaseInfo.GridName;
            titleRow["PhotosCount"] = gInfo.OrderInfo.PhotoS.Count();
            titleRow["outProductOrderInBag"] = outProductOrderInBag.Trim(' ');
            titleRow["IsPrintThumbnail"] = gInfo.OrderInfo.IsPrintThumbnail;
            DtInfo.Rows.Add(titleRow);
            photosCount = gInfo.OrderInfo.PhotoS.Count();
            photosAreas =(decimal) gInfo.OrderInfo.PhotoS.Sum(p=>p.Height*p.Width*2.54*2.54/10000);
            DataSet set = new DataSet("ds");
            set.Tables.Add(dt);
            set.Tables.Add(DtInfo);
            //dt.WriteXml(@"D:\分片小票数据.xml", XmlWriteMode.WriteSchema);
            //2、相应的头信息
            set.WriteXml(@"C:\Windows\xmldata\分片小票数据.xml", XmlWriteMode.WriteSchema);

            fasrReport.RegisterData(dt, "PhotoSize");
            fasrReport.RegisterData(DtInfo, "DtInfo");
            //dt.WriteXml("");

            //gInfo.OrderInfo.CtmName = gInfo.OrderInfo.CtmName.Replace('[', '(').Replace(']', ')');
            //gInfo.OrderInfo.OrderProductName = gInfo.OrderInfo.OrderProductName.Replace('[', '(').Replace(']', ')');
            //gInfo.OrderInfo.Remark = gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')');

            //fasrReport.SetParameterValue("shopName", gInfo.OrderInfo.ShopName);
            //fasrReport.SetParameterValue("orderBarCode", gInfo.OrderInfo.OrderProductId.ToString());
            //fasrReport.SetParameterValue("ctmName", gInfo.OrderInfo.CtmName);
            //fasrReport.SetParameterValue("orderProductName", gInfo.OrderInfo.OrderProductName);
            //fasrReport.SetParameterValue("nextTechName", nextTechName);
            //fasrReport.SetParameterValue("orderRemark", gInfo.OrderInfo.Remark);
            //fasrReport.SetParameterValue("gridName", gInfo.GridBaseInfo.GridName);
            //fasrReport.SetParameterValue("priorityRemark", gInfo.OrderInfo.OrderPriority >= WarnPriority ? "急件" + gInfo.OrderInfo.OrderPriority.ToString() : "");
            //fasrReport.SetParameterValue("factoryName", FACOTRYNAME);
            //fasrReport.SetParameterValue("shopGridName", shopGridName);
            //fasrReport.SetParameterValue("fetchTime", gInfo.OrderInfo.FetchTime);
            //fasrReport.SetParameterValue("photosCount", photosCount);
            fasrReport.SetParameterValue("photosAreas", photosAreas);
            fasrReport.SetParameterValue("outShopName", outShopName);
            if (gInfo.OrderInfo.IsPrintThumbnail)
            {

                //fasrReport.SetParameterValue("Image", MakeThumbnail(gInfo));
            }
            else
            {
                //fasrReport.SetParameterValue("Image", new byte[]{1});
            }
            fasrReport.PrintSettings.ShowDialog = _view.isShowPrintDialog;
            fasrReport.Print();

            _view.CloseDetailPanel();//打印时关闭右边的详细窗体
        }
        #endregion

        //重新改变格子的状态、颜色,当前数量等信息
        private void ReSetGridStatusAndCurCount(List<MyDefineGrid> myGrids)
        {
            foreach (var myGrid in myGrids)
            {
                myGrid.UCg.GridStatus = GetUCGridStatus(myGrid.gridInfo);
                if (myGrid.gridInfo == null || myGrid.gridInfo.OrderInfo == null)
                {
                    myGrid.UCg.CurPicCount = 0;
                }
                else
                {
                    myGrid.UCg.CurPicCount = myGrid.gridInfo.OrderInfo.PhotoS.Count(p => p.Status == (int)PhotoStatus.FenPian);
                }
            }
        }

        //将输入的字符串验定是滞为数字后转换为条码
        private string ConvertToPhotoBarCode(string strInput)
        {
            strInput = strInput.Trim();
            if (strInput.Length < 10)
            {
                if (Regex.IsMatch(strInput, "^[0-9]*$"))//验证是否为数字
                    return "3" + strInput.PadLeft(9, '0');
                else
                {
                    return null;
                }
            }
            else if (strInput.Length == 10 && strInput.StartsWith("3"))
            {
                return strInput;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 将GridInfo_Grid转换为UCGrid控件
        /// </summary>
        /// <param name="sourceGridInfo"></param>
        /// <returns></returns>
        private void IntiUCGrid(List<GridInfo_Grid> sourceGridInfo)
        {
            if (GirdControls == null)
            {
                GirdControls = new Dictionary<int, MyDefineGrid>();
            }
            //排序
            sourceGridInfo = sourceGridInfo.OrderBy(g => Convert.ToInt32(g.GridBaseInfo.GridName.Substring(1))).ToList();
            foreach (var item in sourceGridInfo)
            {
                GirdControls.Add(item.GridBaseInfo.GridId, new MyDefineGrid()
                {
                    UCg = CreateUcgGrid(item),
                    gridInfo = item
                });
            }
        }

        /// <summary>
        /// 用格子信息重新初始化格子
        /// </summary>
        /// <param name="ucg"></param>
        /// <param name="gInfo"></param>
        private void ReSetUCGrid(UCGrid ucg, GridInfo_Grid gInfo)
        {
            ucg.GridStatus = GetUCGridStatus(gInfo);
            if (gInfo != null && gInfo.OrderInfo != null)
            {
                ucg.CurPicCount = gInfo.OrderInfo.InGridCount;
                ucg.PicCout = gInfo.OrderInfo.PhotoCount;
                ucg.OrderProductName = gInfo.OrderInfo.OrderProductName;
                ucg.ShopName = gInfo.OrderInfo.ShopName;
                ucg.CtmName = gInfo.OrderInfo.CtmName;

                #region 注册双击、单击事件
                #region 先取消再添加取消双击点击事件
                try
                {
                    ucg.DoubleClick -= ucg_DoubleClick;
                    ucg.Click -= ucg_Click;

                    ucg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCout.Click -= new EventHandler(labCout_Click);

                    ucg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCurr.Click -= new EventHandler(labCout_Click);

                    ucg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labGridName.Click -= new EventHandler(labCout_Click);

                    ucg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labProductName.Click -= new EventHandler(labCout_Click);

                    ucg.labShopName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labShopName.Click -= new EventHandler(labCout_Click);

                    ucg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion

                ucg.DoubleClick += new EventHandler(ucg_DoubleClick);
                ucg.Click += new EventHandler(ucg_Click);

                ucg.labCout.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labCout.Click += new EventHandler(labCout_Click);

                ucg.labCurr.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labCurr.Click += new EventHandler(labCout_Click);

                ucg.labGridName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labGridName.Click += new EventHandler(labCout_Click);

                ucg.labProductName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labProductName.Click += new EventHandler(labCout_Click);

                ucg.labShopName.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.labShopName.Click += new EventHandler(labCout_Click);

                ucg.label1.DoubleClick += new EventHandler(labCout_DoubleClick);
                ucg.label1.Click += new EventHandler(labCout_Click);

                #endregion
            }
            else
            {
                ucg.CurPicCount = 0;
                ucg.PicCout = 0;
                ucg.OrderProductName = "";
                ucg.ShopName = "";

                #region 取消双击点击事件
                try
                {
                    ucg.DoubleClick -= ucg_DoubleClick;
                    ucg.Click -= ucg_Click;

                    ucg.labCout.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCout.Click -= new EventHandler(labCout_Click);

                    ucg.labCurr.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labCurr.Click -= new EventHandler(labCout_Click);

                    ucg.labGridName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labGridName.Click -= new EventHandler(labCout_Click);

                    ucg.labProductName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labProductName.Click -= new EventHandler(labCout_Click);

                    ucg.labShopName.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.labShopName.Click -= new EventHandler(labCout_Click);

                    ucg.label1.DoubleClick -= new EventHandler(labCout_DoubleClick);
                    ucg.label1.Click -= new EventHandler(labCout_Click);
                }
                catch { }
                #endregion
            }
        }


        /// <summary>
        /// 根据格子的显示实体，得到要应的控件
        /// </summary>
        /// <param name="gInfo"></param>
        /// <returns></returns>
        private UCGrid CreateUcgGrid(GridInfo_Grid gInfo)
        {
            UCGrid ucg = new UCGrid()
            {
                GridId = gInfo.GridBaseInfo.GridId,
                GridName = gInfo.GridBaseInfo.GridName,
                //GridStatus = GetUCGridStatus(gInfo),
                Width = UGridWidth,
                Height = UGridHeigth,
                Dock = DockStyle.Fill
            };

            ReSetUCGrid(ucg, gInfo);

            return ucg;
        }

        void labCout_Click(object sender, EventArgs e)
        {
            ucg_Click(((Control)sender).Parent, e);
        }

        void labCout_DoubleClick(object sender, EventArgs e)
        {
            ucg_DoubleClick(((Control)sender).Parent, e);
        }

        void ucg_Click(object sender, EventArgs e)//单击，就是选中
        {
            MyDefineGrid myGrid;
            GirdControls.TryGetValue(((UCGrid)sender).GridId, out myGrid);
            //if (myGrid.gridInfo.OrderInfo!=null)
            //{
            SetGridSelected(myGrid);
            //}

        }

        void ucg_DoubleClick(object sender, EventArgs e)
        {
            MyDefineGrid myGrid;
            GirdControls.TryGetValue(((UCGrid)sender).GridId, out myGrid);
            //if (myGrid.gridInfo.OrderInfo!=null)
            //{
            //SetGridSelected(myGrid);

            //将格子中的图片信息绑定到右边滑出来的窗体中
            _view.ShowOrderDetail(myGrid);
            //}

        }

        /// <summary>
        /// 根据格子中照片的信息，得到格子相应的状态
        /// </summary>
        /// <param name="gInfo"></param>
        /// <returns></returns>
        private UCGridStatus GetUCGridStatus(GridInfo_Grid gInfo)
        {
            UCGridStatus resultStatus = UCGridStatus.Normal;
            if (gInfo != null && gInfo.OrderInfo != null)
            {

                if (gInfo.OrderInfo.PhotoCount == gInfo.OrderInfo.PhotoS.Count(p => p.Status == (int)PhotoStatus.FenPian || p.Status == (int)PhotoStatus.Printed))
                {
                    resultStatus = UCGridStatus.OutOver;
                }
                if (gInfo.GridBaseInfo.FirstEnterTime.Subtract(DateTime.Now).TotalMinutes >= DataTransfer.CurSubArea.OutTimeAlarmTime)
                {
                    resultStatus = UCGridStatus.TimeOut;
                }
            }

            return resultStatus;
        }

        //得到图片的缩略图，如果没有缩略图就加载原图
        private RasterImage GetStampPic(string picPath, RasterCodecs codecs)
        {
            //RasterImageListItem rtmItrm = new RasterImageListItem();
            RasterImage image1 = null;
            CodecsThumbnailOptions options = CodecsThumbnailOptions.Default;
            options.LoadStamp = true;
            options.Resample = true;
            options.MaintainAspectRatio = false;
            try
            {
                image1 = codecs.ReadThumbnail(picPath, options, 1);
            }
            catch
            {
                options.LoadStamp = false;
                try
                {
                    image1 = codecs.ReadThumbnail(picPath, options, 1);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("找不到图片,请确认图片是否被移走!/n/r" + ex.Message);
                }
            }
            return image1;
            //rtmItrm = new RasterImageListItem(image1, 1, inPhotoId.ToString());
            //return rtmItrm;
        }


        delegate List<RasterImageListItem> ShowImgInFrmDelegate();
        /// <summary>
        /// 得到被选中的格子的图片的略缩图
        /// </summary>
        /// <returns></returns>
        internal void GetImageList()
        {
            ShowImgInFrmDelegate dlShowImg = ShowImgInFrm;
            IAsyncResult rl = dlShowImg.BeginInvoke(null, null);
            while (!rl.IsCompleted)
            {
                _view.SetProcessGo();
                Thread.Sleep(200);
            }
            _view.ShowImg(dlShowImg.EndInvoke(rl));
            _view.SetProcessOver();

        }

        //在界面中显示图片
        private List<RasterImageListItem> ShowImgInFrm()
        {
            List<RasterImageListItem> listImg = new List<RasterImageListItem>();
            RasterCodecs codecs = null;
            MyDefineGrid myGrid = _curSelectedGridList.First();
            if (myGrid.gridInfo.OrderInfo != null)
            {
                foreach (var pi in myGrid.gridInfo.OrderInfo.PhotoS.Where(p => p.Status != (int)PhotoStatus.FenPian).ToList())
                {
                    if (pi.Image == null)
                    {
                        try
                        {
                            if (codecs == null)
                            {
                                RasterCodecs.Startup();
                                codecs = new RasterCodecs();
                            }
                            pi.Image = GetStampPic(pi.PicPath, codecs);
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                    listImg.Add(new RasterImageListItem(pi.Image.Clone(), 1, pi.PhotoId.ToString()));
                }

                if (codecs != null)
                {
                    codecs.Dispose();
                    RasterCodecs.Shutdown();
                }
            }
            return listImg;
            //_view.ShowImg(listImg);
        }

        //清空格子
        internal void ClearSelectedGrid()
        {
            //从数据库中清空格子中的照片的状态
            //更新内存数据中照片的状态
            //更新界面显示
            if (_curSelectedGridList.Count > 0)
            {
                if (DialogResult.Yes == MessageBox.Show("确认要清空这些格子？", "警报", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    int result = _mainBLL.ClearSelectedGrid(_curSelectedGridList.Select(g => g.gridInfo).ToList());
                    if (result == 1)//操作成功，更新内存数据中照片的状态
                    {
                        //_curSelectedGridList.ForEach(g => g.gridInfo.OrderInfo.PhotoS.ForEach(p => { if (p.Status == (int)PhotoStatus.FenPian) { p.Status = (int)PhotoStatus.Printed; } }));
                        _curSelectedGridList.ForEach(g => g.gridInfo.OrderInfo = null);

                        //ReSetGridStatusAndCurCount(_curSelectedGridList);
                        foreach (var myGrid in _curSelectedGridList)
                        {
                            //清空格子                 
                            ReSetUCGrid(myGrid.UCg, null);
                        }
                        _curSelectedGridList.Clear();

                        SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下
                        MessageBox.Show("清空成功！");
                    }

                    else
                    {
                        //报相关的错误
                        MessageBox.Show("清空失败！");
                    }
                }

                _view.CloseDetailPanel();//打印时关闭右边的详细窗体
            }
            else
            {
                MessageBox.Show("没有选中要清空的格子!");
            }
        }

        //强制打印选中的格子
        internal void ForcePrint()
        {
            string shopGridName = string.Empty;
            if (DialogResult.Yes != MessageBox.Show("确认需要强制打印格子中的照片？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                return;
            }
            int result = 1;
            string strNextTechName = string.Empty;
            string outProductOrderInBag=string.Empty;
            //先从数据库中完成该格子
            if (_curSelectedGridList.Count != 1)
            {
                MessageBox.Show("请单选中需要打印的格子！");
                return;
            }
            GridBLL_Grid _gridBLL = new GridBLL_Grid();
            MyDefineGrid myGrid = _curSelectedGridList.First();

            result = _gridBLL.ForcePrintGrid(myGrid.gridInfo, DataTransfer.curTechId, DataTransfer.OpUid, out strNextTechName, out shopGridName,out outProductOrderInBag);
            if (result == 1)
            {
                //组织打印数据进行打印
                PintGrid(myGrid.gridInfo, strNextTechName, shopGridName, outProductOrderInBag,"");

                //清空格子
                myGrid.gridInfo.OrderInfo = null;
                ReSetUCGrid(myGrid.UCg, null);
                SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下

            }
            else
            {
                //显示错误信息
                MessageBox.Show(string.Format("操作失败,相关信息为：产品号：{0}；当前节点ID:{1};操作员ID：{2};", myGrid.gridInfo.OrderInfo.OrderProductId, DataTransfer.curTechId, DataTransfer.OpUid));
            }

        }

        /// <summary>
        /// 当选中的格子中的照片加急
        /// </summary>
        internal void PrioritySelectedGird()
        {
            if (MessageBox.Show("确认要对选中的格子进行清柜操作？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }
            int result = 1;
            if (_curSelectedGridList.Count > 0)
            {
                result = _mainBLL.PriorityGrid(_curSelectedGridList.Select(g => g.gridInfo).ToList());
                if (result == 1)
                {
                    MessageBox.Show("清柜成功！");
                }
                else
                {
                    //失败
                }
            }
            else
            {
                MessageBox.Show("请先选择需要清柜的格子！");
            }
        }

        internal void ConditionPriorityGrid()
        {
            int conditionNum = 0;
            int result = 1;


            FrmPhotoNum frmNum = new FrmPhotoNum();
            if (frmNum.ShowDialog() == DialogResult.OK)
            {
                conditionNum = Convert.ToInt32(frmNum.spinEditNum.Value);
            }
            else
            {
                return;
            }

            if (conditionNum == 0)
            {
                if (MessageBox.Show("是否需要将全部格子都清柜？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    result = _mainBLL.PriorityGrid(GirdControls.Values.Where(g => g.gridInfo.OrderInfo != null).Select(g => g.gridInfo).ToList());
                }
            }
            else
            {
                result = _mainBLL.PriorityGrid(GirdControls.Values.Where(g => g.gridInfo.OrderInfo != null && g.gridInfo.OrderInfo.PhotoS.Count(p => p.Status != (int)PhotoStatus.FenPian) <= conditionNum).Select(g => g.gridInfo).ToList());
            }

            if (result == 1)
            {
                MessageBox.Show("操作成功！");
            }
            else
            {
                MessageBox.Show("操作失败！");
            }
        }

        //刷新格子中的数据
        internal void RefreshData()
        {
            List<GridInfo_Grid> listGrid = null;
            int result = _mainBLL.GetHasProductGridInfoBySubAreaId(DataTransfer.CurSubArea.SubAreaID, out listGrid, 2);
            MyDefineGrid myGrid;
            foreach (var gInfo in listGrid)
            {
                GirdControls.TryGetValue(gInfo.GridBaseInfo.GridId, out myGrid);
                if (myGrid != null)
                {
                    myGrid.gridInfo = gInfo;
                    ReSetUCGrid(myGrid.UCg, gInfo);
                }
                myGrid = null;
            }
            myGrid = null;

            //清空那里有，但是刷新后没有的格子
            foreach (var notInGinfo in GirdControls.Values.Where(mg => mg.gridInfo.OrderInfo != null).Select(mg => mg.gridInfo).Except(listGrid).ToList())
            {                 //清空这些格子
                GirdControls.TryGetValue(notInGinfo.GridBaseInfo.GridId, out myGrid);
                if (myGrid != null)
                {
                    notInGinfo.OrderInfo = null;
                    ReSetUCGrid(myGrid.UCg, null);
                }
                myGrid = null;
            }
            myGrid = null;
            _curSelectedGridList.Clear();
            SetGridSelected(GirdControls.Values.FirstOrDefault(g => g.gridInfo.OrderInfo != null));//格子中不为空的任意一下
        }

        public void ReBackOrder()
        {
            MyDefineGrid myGrid = _curSelectedGridList.First();
            int intPrint = (int)PhotoStatus.Printed;

            _view.ShowFandan(myGrid.gridInfo.OrderInfo.PhotoS.Where(p => p.Status == intPrint).ToList());
        }

        internal void SearchByShopName()//查找某商户占用多少个商子
        {
            List<string> shopList = GirdControls.Values.Select(g => g.UCg.ShopName).Where(sn => !string.IsNullOrEmpty(sn)).ToList();
            if (shopList.Count < 1)
            {
                MessageBox.Show("所有格子都为空!");
                return;
            }
            FrmSelShop frm = new FrmSelShop();

            frm.ListShop = shopList;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                //frm.SelectedShopName
                List<MyDefineGrid> myGridList = GirdControls.Values.Where(g => g.UCg.ShopName == frm.SelectedShopName).ToList();
                if (myGridList.Count > 0)
                {
                    ReSetGridStatusAndCurCount(_curSelectedGridList);//还原上一些格子本来的状态
                    foreach (var myGrid in myGridList)
                    {
                        SetSelectGridList(myGrid, 0);
                        myGrid.UCg.GridStatus = UCGridStatus.Selected;
                    }
                }

            }
        }

        /// <summary>
        /// 是否直接分堆
        /// </summary>
        /// <returns></returns>
        public bool IsAutoAssignShop()
        {
            return _mainBLL.IsAutoAssignShop();
        }
    }
}
